/**
 * 用户管理相关API
 */
import { get, post, put, del } from './index'
import type {
  ApiResponse,
  PaginatedResponse,
  PaginationParams,
  User
} from '@/types'

// 用户管理
export const getUsers = (params?: PaginationParams & {
  search?: string
  role?: string
  is_active?: boolean
  department?: string
  class_id?: number
}) => {
  return get<ApiResponse<PaginatedResponse<User>>>('/api/v1/users/users/', params)
}

export const getUser = (id: number) => {
  return get<ApiResponse<User>>(`/api/v1/users/users/${id}/`)
}

export const createUser = (data: {
  username: string
  email: string
  password: string
  first_name: string
  last_name: string
  role: string
  phone?: string
  department?: string
  class_id?: number
  is_active?: boolean
}) => {
  return post<ApiResponse<User>>('/api/v1/users/users/', data)
}

export const updateUser = (id: number, data: Partial<User>) => {
  return put<ApiResponse<User>>(`/api/v1/users/users/${id}/`, data)
}

export const deleteUser = (id: number) => {
  return del(`/api/v1/users/users/${id}/`)
}

export const resetUserPassword = (id: number, data: { new_password: string }) => {
  return post<ApiResponse<{ message: string }>>(`/api/v1/users/users/${id}/reset-password/`, data)
}

export const toggleUserStatus = (id: number) => {
  return post<ApiResponse<User>>(`/api/v1/users/users/${id}/toggle-status/`)
}

// 批量操作
export const batchCreateUsers = (data: { users: any[] }) => {
  return post<ApiResponse<{ success_count: number; failed_count: number; errors: string[] }>>(
    '/api/v1/users/users/batch-create/',
    data
  )
}

export const batchUpdateUsers = (data: { user_ids: number[]; updates: Partial<User> }) => {
  return post<ApiResponse<{ success_count: number; failed_count: number; errors: string[] }>>(
    '/api/v1/users/users/batch-update/',
    data
  )
}

export const batchDeleteUsers = (data: { user_ids: number[] }) => {
  return post<ApiResponse<{ success_count: number; failed_count: number; errors: string[] }>>(
    '/api/v1/users/users/batch-delete/',
    data
  )
}

export const exportUsers = (params: {
  format: 'excel' | 'csv' | 'pdf'
  role?: string
  department?: string
  is_active?: boolean
}) => {
  return get('/api/v1/users/users/export/', params, {
    responseType: 'blob'
  })
}

export const importUsers = (file: File) => {
  const formData = new FormData()
  formData.append('file', file)
  return post<ApiResponse<{ imported: number; skipped: number; errors: string[] }>>(
    '/api/v1/users/users/import/',
    formData,
    {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
  )
}

// 角色管理
export const getRoles = () => {
  return get<ApiResponse<Array<{ id: string; name: string; description: string; permissions: string[] }>>>(
    '/api/v1/users/roles/'
  )
}

export const getRole = (id: string) => {
  return get<ApiResponse<{ id: string; name: string; description: string; permissions: string[] }>>(
    `/api/v1/users/roles/${id}/`
  )
}

export const createRole = (data: {
  name: string
  description: string
  permissions: string[]
}) => {
  return post<ApiResponse<{ id: string; name: string; description: string; permissions: string[] }>>(
    '/api/v1/users/roles/',
    data
  )
}

export const updateRole = (id: string, data: {
  name?: string
  description?: string
  permissions?: string[]
}) => {
  return put<ApiResponse<{ id: string; name: string; description: string; permissions: string[] }>>(
    `/api/v1/users/roles/${id}/`,
    data
  )
}

export const deleteRole = (id: string) => {
  return del(`/api/v1/users/roles/${id}/`)
}

// 权限管理
export const getPermissions = () => {
  return get<ApiResponse<Array<{
    id: string
    name: string
    codename: string
    description: string
    content_type: string
  }>>>(
    '/api/v1/users/permissions/'
  )
}

// 部门管理
export const getDepartments = () => {
  return get<ApiResponse<Array<{
    id: number
    name: string
    description: string
    parent: number | null
    user_count: number
  }>>>(
    '/api/v1/users/departments/'
  )
}

export const createDepartment = (data: {
  name: string
  description?: string
  parent?: number
}) => {
  return post<ApiResponse<{ id: number; name: string; description: string; parent: number | null }>>(
    '/api/v1/users/departments/',
    data
  )
}

export const updateDepartment = (id: number, data: {
  name?: string
  description?: string
  parent?: number
}) => {
  return put<ApiResponse<{ id: number; name: string; description: string; parent: number | null }>>(
    `/api/v1/users/departments/${id}/`,
    data
  )
}

export const deleteDepartment = (id: number) => {
  return del(`/api/v1/users/departments/${id}/`)
}

// 班级管理
export const getClasses = (params?: PaginationParams & {
  department?: number
  search?: string
}) => {
  return get<ApiResponse<PaginatedResponse<{
    id: number
    name: string
    department: string
    teacher: User
    student_count: number
    description: string
    created_at: string
  }>>>('/api/v1/users/classes/', params)
}

export const getClass = (id: number) => {
  return get<ApiResponse<{
    id: number
    name: string
    department: string
    teacher: User
    students: User[]
    description: string
    created_at: string
  }>>(`/api/v1/users/classes/${id}/`)
}

export const createClass = (data: {
  name: string
  department: string
  teacher_id: number
  description?: string
  student_ids?: number[]
}) => {
  return post<ApiResponse<{
    id: number
    name: string
    department: string
    teacher: User
    description: string
    created_at: string
  }>>('/api/v1/users/classes/', data)
}

export const updateClass = (id: number, data: {
  name?: string
  department?: string
  teacher_id?: number
  description?: string
  student_ids?: number[]
}) => {
  return put<ApiResponse<{
    id: number
    name: string
    department: string
    teacher: User
    description: string
    created_at: string
  }>>(`/api/v1/users/classes/${id}/`, data)
}

export const deleteClass = (id: number) => {
  return del(`/api/v1/users/classes/${id}/`)
}

export const addStudentsToClass = (classId: number, data: { student_ids: number[] }) => {
  return post<ApiResponse<{ added_count: number; failed_count: number; errors: string[] }>>(
    `/api/v1/users/classes/${classId}/add-students/`,
    data
  )
}

export const removeStudentsFromClass = (classId: number, data: { student_ids: number[] }) => {
  return post<ApiResponse<{ removed_count: number; failed_count: number; errors: string[] }>>(
    `/api/v1/users/classes/${classId}/remove-students/`,
    data
  )
}

// 用户统计
export const getUserStatistics = (params?: {
  department?: number
  role?: string
  start_date?: string
  end_date?: string
}) => {
  const queryParams = new URLSearchParams()
  Object.entries(params || {}).forEach(([key, value]) => {
    if (value) queryParams.append(key, String(value))
  })

  const query = queryParams.toString()
  const url = query ? `/api/v1/users/statistics/?${query}` : '/api/v1/users/statistics/'

  return get<ApiResponse<{
    total_users: number
    active_users: number
    inactive_users: number
    role_distribution: Record<string, number>
    department_distribution: Array<{
      department_name: string
      user_count: number
    }>
    recent_registrations: Array<{
      date: string
      count: number
    }>
    login_activity: Array<{
      date: string
      active_users: number
    }>
  }>>(url)
}

// 当前用户相关
export const getCurrentUser = () => {
  return get<ApiResponse<User>>('/api/v1/users/me/')
}

export const updateCurrentUser = (data: Partial<User>) => {
  return put<ApiResponse<User>>('/api/v1/users/me/', data)
}

export const changePassword = (data: {
  old_password: string
  new_password: string
  confirm_password: string
}) => {
  return post<ApiResponse<{ message: string }>>('/api/v1/users/me/change-password/', data)
}

export const updateAvatar = (file: File) => {
  const formData = new FormData()
  formData.append('avatar', file)
  return post<ApiResponse<{ avatar_url: string }>>(
    '/api/v1/users/me/update-avatar/',
    formData,
    {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
  )
}

// 活动日志
export const getUserActivityLogs = (params?: PaginationParams & {
  user_id?: number
  action?: string
  start_date?: string
  end_date?: string
}) => {
  return get<ApiResponse<PaginatedResponse<{
    id: number
    user: User
    action: string
    description: string
    ip_address: string
    user_agent: string
    timestamp: string
  }>>>('/api/v1/users/activity-logs/', params)
}

// 导出统一的用户API对象
export const userApi = {
  // 用户管理
  getUsers,
  getUser,
  createUser,
  updateUser,
  deleteUser,
  resetUserPassword,
  toggleUserStatus,

  // 批量操作
  batchCreateUsers,
  batchUpdateUsers,
  batchDeleteUsers,
  exportUsers,
  importUsers,

  // 角色管理
  getRoles,
  getRole,
  createRole,
  updateRole,
  deleteRole,

  // 权限管理
  getPermissions,

  // 部门管理
  getDepartments,
  createDepartment,
  updateDepartment,
  deleteDepartment,

  // 班级管理
  getClasses,
  getClass,
  createClass,
  updateClass,
  deleteClass,
  addStudentsToClass,
  removeStudentsFromClass,

  // 统计分析
  getUserStatistics,

  // 当前用户
  getCurrentUser,
  updateCurrentUser,
  changePassword,
  updateAvatar,

  // 活动日志
  getUserActivityLogs
}